<template>
  <div>
    <!-- 面包屑   -->
    <div style="margin-bottom: 30px">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>车辆基本信息</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div style="margin: 10px 0">
      <el-input style="width: 200px" placeholder="请输入车牌号"
                v-model="name" suffix-icon="el-icon-search"></el-input>
      <el-input style="width: 200px" placeholder="请输入车主名"
                v-model="username" suffix-icon="el-icon-user" class="ml-5 mr-5"></el-input>
            <template>
              <el-select v-model="gender" placeholder="请选择车辆类型">
                <el-option label="全部" value=" "></el-option>
                <el-option label="小型车" value="小型车"></el-option>
                <el-option label="大型车" value="大型车"></el-option>
              </el-select>
            </template>
      <el-button class="ml-5" type="primary" @click="search">搜索</el-button>
      <el-button class="ml-5" type="warning" @click="reset">重置</el-button>
    </div>

    <div style="margin: 10px 0">
      <el-button type="primary" @click="handleAdd" class="mr-5">新增 <i class="el-icon-circle-plus-outline"></i>
      </el-button>
      <el-popconfirm
          confirm-button-text='确定'
          cancel-button-text='再想想'
          icon="el-icon-info"
          icon-color="red"
          title="确定批量删除吗？"
          @confirm="delBatch">
        <el-button type="danger" slot="reference" class="mr-5">批量删除 <i class="el-icon-remove-outline"></i></el-button>
      </el-popconfirm>
    </div>
    <!-- 表的主体   -->
    <el-table :data="tableData" border stripe
              @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="40">
      </el-table-column>
      <el-table-column prop="id" label="id">
      </el-table-column>
      <el-table-column prop="vehicleId" label="车牌号">
      </el-table-column>
      <el-table-column prop="vehicleStytle" label="车型">
      </el-table-column>
      <el-table-column prop="vehicleModel" label="车别">
      </el-table-column>
      <el-table-column prop="staffBasicInfo.trueName" label="驾驶员">
      </el-table-column>
      <el-table-column prop="" label="车辆图片" width="75" align="center">
        <template slot-scope="scope">
          <img :src="scope.row.vehiclePhoto" alt="" style="width: 50px;height: 50px"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="" align="center" min-width="100">
        <template slot-scope="scope">
          <el-button type="success" @click="handleEdit(scope.row)" class="mr-5">
            查看<i class="el-icon-edit"></i>
          </el-button>
          <el-popconfirm
              confirm-button-text='确定'
              cancel-button-text='再想想'
              icon="el-icon-info"
              icon-color="red"
              title="确定删除吗？"
              @confirm="del(scope.row.id)">
            <el-button type="danger" slot="reference">删除 <i class="el-icon-remove-outline"></i></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 页码导航栏   -->
    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[5, 10, 15, 20]"
          :page-size=pageSize
          layout="total, sizes, prev, pager, next, jumper"
          :total=total>
      </el-pagination>
    </div>
    <!--        车辆信息的弹窗-->
    <el-dialog title="车辆信息" :visible.sync="dialogFormVisible" width="50%" :close-on-click-modal="false">
      <el-form :model="vehicle" :inline="true" :rules="rules" ref="vehicle">
        <el-form-item label="车牌号" label-width="100px" prop="vehicleId">
          <el-input v-model="vehicle.vehicleId" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="车型" label-width="100px" prop="vehicleStytle">
          <el-select v-model="vehicle.vehicleStytle" placeholder="请选择车型">
            <el-option value="微型车" ></el-option>
            <el-option value="小型车" ></el-option>
            <el-option value="中型车" ></el-option>
            <el-option value="大型车" ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车别" label-width="100px" prop="vehicleModel">
          <el-select v-model="vehicle.vehicleModel" placeholder="请选择车别">
            <el-option value="小型货车" ></el-option>
            <el-option value="微型货车" ></el-option>
            <el-option value="中型货车" ></el-option>
            <el-option value="大型货车" ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="驾驶员" prop="driver"  label-width="100px">
        <el-select v-model="vehicle.driver" placeholder="请选择驾驶员">
          <el-option
              v-for="item in drivers"
              :key="item.staffId"
              :label="item.trueName"
              :value="item.staffId">
          </el-option>
        </el-select>
      </el-form-item>
        <el-form-item label="车辆图片" label-width="100px" prop="">
          <el-upload
              class="avatar-uploader"
              action="http://localhost/file/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess1"
              :before-upload="beforeAvatarUpload">
            <img v-if="vehicle.vehiclePhoto" :src="vehicle.vehiclePhoto" class="avatar" alt="">
            <img v-else-if="vehicleImg" :src="vehicleImg" class="avatar" alt="">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible=false">取 消</el-button>
        <el-button type="primary" @click="save('vehicle')">{{ btnText }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import request from "@/utils/request";
export default {
  name: "Vehicle",
  data() {
    return {
      tableData: [],
      currentPage: 1,
      name: "",
      username: "",
      gender: "",
      pageSize: 5,
      total: 0,
      dialogFormVisible: false,
      btnText: "",
      vehicle: {},
      multipleSelection: [],
      vehicleImg: '',
      drivers:{},
      rules: {
        // name: [
        //   {required: true, message: '请输入姓名', trigger: 'blur'},
        // ],
        // gender: [
        //   {required: true, message: '请选择性别', trigger: 'blur'},
        // ],
        // phone: [
        //   {required: true, message: '请输入电话号码', trigger: 'blur'},
        //   {min: 11, max: 11, message: '请输入长度为11个数字的电话号码', trigger: 'blur'}
        // ],
        // username: [
        //   {required: true, message: '请输入用户名', trigger: 'blur'},
        //   {min: 3, message: '长度在 3 个字符以上', trigger: 'blur'}
        // ],
        // password: [
        //   {required: true, message: '请输入密码', trigger: 'blur'},
        //   {min: 6, message: '长度在 6 个字符以上', trigger: 'blur'}
        // ]
      },
    }
  },
  created() {
    this.load()
  },
  methods: {
    // 分页查询接口
    load() {
      request.get("/vehicleInfo/get",
          {params: {pageNum: this.currentPage, pageSize: this.pageSize}}
      ).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
        this.currentPage = res.data.current
        this.pageSize = res.data.size
      })
      request.get("/staff/get").then(res => {
        this.drivers = res.data
      })
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.currentPage = pageNum
      this.load()
    },
    handleAdd() {
      this.btnText = "添加"
      this.vehicle = {}
      this.dialogFormVisible = true
    },
    handleEdit(row) {
      this.btnText = "修改"
      this.dialogFormVisible = true
      this.vehicle = Object.assign({}, row)
    },
    // 增加修改数据接口
    save(vehicle) {
      this.$refs[vehicle].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false
          // console.log(this.vehicle)
          if (this.btnText === '添加') {
            request.post("/vehicleInfo/add", this.vehicle).then(res => {
              if (res) {
                this.$message.success(this.btnText + "成功")
                this.load()
                this.vehicleImg = ""
              } else {
                this.$message.error(this.btnText + "失败")
              }
            })
          } else {
            request.put("/vehicleInfo/update", this.vehicle).then(res => {
              if (res) {
                this.$message.success(this.btnText + "成功")
                this.load()
                this.vehicleImg = ""
              } else {
                this.$message.error(this.btnText + "失败")
              }
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 单个删除
    del(id) {
      request.delete("/vehicleInfo/del/" + id).then(res => {
        if (res.code === 200) {
          this.$message.success("删除成功")
          this.load()
        } else {
          this.$message.error("删除失败")
        }
      })
      console.log(id)
    },
    handleSelectionChange(val) {
      // console.log(val)
      this.multipleSelection = val
    },
    // 批量删除接口
    delBatch() {
      //map函数：数组的每个元素都执行一个给定的函数，返回值仍为一个数组
      let ids = this.multipleSelection.map(v => v.id)
      console.log(ids)
      if (ids.length !== 0) {
        request.delete("/vehicleInfo/del/" + ids.toString(),).then(res => {
          if (res) {
            this.$message.success("批量删除成功")
            this.load()
          } else {
            this.$message.error("批量删除失败")
          }
        })
      } else {
        this.$message.warning("请选择要删除的数据")
      }
    },
    search(){

    },
    reset() {
      this.username = ""
      this.name = ""
      this.gender = ""
      this.load()
    },
    handleAvatarSuccess1(res, file) {//处理头像
      this.vehicleImg = URL.createObjectURL(file.raw);
      this.vehicle.vehiclePhoto = res
    },
    beforeAvatarUpload(file) {
      const isJPG_PNG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG_PNG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG_PNG && isLt2M;
    }
  }
}
</script>

<style scoped>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>